var rest = require('rest');
var wh = require('when');

exports.register = function (app) {
    function getToken(app) {
        var url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + app.appid + "&secret=" + app.secret;
        return rest(url).then(function (data) {
            var data = JSON.parse(data.entity);
            var value = data.access_token;
            var startTime = Date.now();
            app.locals.token = {
                value: value,
                startTime: startTime
            };
            console.log("token:" + app.locals.token.value);
            return app.locals.token;
        });
    }

    if (app.locals.token) {
        var startTime = app.locals.token.startTime;
        var currentTime = Date.now();
        var time = currentTime - startTime;
        if (time > 1.5 * 60 * 60) { // 1.5小时后过期
            return getToken(app);
        } else {
            console.log("stored token" + app.locals.token.value);
            return wh.resolve(app.locals.token);
        }
    } else {
        return getToken(app);
    }
}

